package cn.maihe.elg.operation.interceptor;

import cn.maihe.elg.operation.utils.IdGenerate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description
 * @Author WJH
 * @Date 2021/10/09
 */
@Component
public class ElgLogInterceptor implements HandlerInterceptor {
    private final static String TRACE_ID = "traceId";
    private static final Logger LOGGER = LoggerFactory.getLogger(ElgLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String xForwardedForHeader = httpServletRequest.getHeader("X-Forwarded-For");
        String remoteIp = httpServletRequest.getRemoteAddr();
        String traceId = IdGenerate.getIdStr();
        LOGGER.debug("put traceId[{}] to logger", traceId);
        LOGGER.debug("traceId:{}, clientIp:{}, X-Forwarded-For:{}", traceId, remoteIp, xForwardedForHeader);
        MDC.put(TRACE_ID, traceId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        String traceId = MDC.get(TRACE_ID);
        LOGGER.debug("remove traceId:{} from logger", traceId);
        MDC.remove(TRACE_ID);
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
